<?php
/**
 * Created by PhpStorm.
 * User: js
 * Date: 2018/10/10
 * Time: 10:22
 */

namespace app\modules\api\controllers;


use app\models\Agent;
use app\models\Goods;
use app\models\Order;
use app\models\Setting;
use app\models\User;
use app\models\LiveStream;
use app\models\OrderRefund;
use app\models\OrderDetail;
use app\modules\api\models\LiveTimeForm;
use app\modules\api\models\OpenLiveForm;
use app\modules\api\models\CloseLiveForm;
use app\modules\mch\models\LiveStreamForm;
use app\modules\mch\models\ShareOrderForm;
use app\modules\mch\models\ShareListForm;


class AgentController extends Controller
{

    //登录
    public function actionAgentLogin()
    {

        $account = Agent::findOne(['account' => \yii::$app->request->get('account'), 'pwd' => \yii::$app->request->get('pwd'),'store_id'=>$this->store->id, 'is_delete' => 0]);
        if($account != 0){
            $this->renderJson((object)[
                'code' => 0,
                'msg' => 'success',
                'data' => [
                    'account' => $account['id'],
                ],
            ]);
        }else{
            $this->renderJson((object)[
                'code' => 1,
                'msg' => '账号或密码错误',
                'data' => [
                    'account' => $account,
                ],
            ]);
        }

    }
    //生成随机数
    public function randnum($length){
        $pattern = '1234567890abcdefghijklmnopqrstuvwxyz 
               ABCDEFGHIJKLOMNOPQRSTUVWXYZ';
        $key='';
        for($i=0;$i<$length;$i++)
        {
            $key .= $pattern{mt_rand(0,35)};    //生成php随机数
        }
        return $key;
    }
    /**
     * 获取推流地址
     * 如果不传key和过期时间，将返回不含防盗链的url
     * @param domain 您的推流域名
     *        streamId 您用来区别不同推流地址的唯一流ID
     *        key 安全密钥
     *        time 过期时间 sample 2016-11-12 12:00:00
     * @return String url */
    function getPushUrl($domain, $streamName, $key = null, $time = null){
        if($key && $time){
            $txTime = strtoupper(base_convert(strtotime($time),10,16));
            //txSecret = MD5( KEY + streamName + txTime )
            $txSecret = md5($key.$streamName.$txTime);
            $ext_str = "?".http_build_query(array(
                    "txSecret"=> $txSecret,
                    "txTime"=> $txTime
                ));
        }
        return $domain.$streamName  . (isset($ext_str) ? $ext_str : "");
    }


    /**
     * 获取播放地址
     * @param domain 您的播放域名
     *        streamId 您用来区别不同推流地址的唯一流ID
     * @return String url */

    function getPlayUrl($domain, $streamId){
        return $domain.'/'.$streamId;
    }

    //开启直播
    public function actionOpenLive()
    {
        $form = new OpenLiveForm();
        $form->attributes = \Yii::$app->request->get();
        $form->wechat_app_id = $this->store->id;
        //获取平台id
        $pingtai = $this->GetPingTai();
        $ping_stream = LiveStream::findOne(['wechat_app_id'=>$pingtai]);
        $own_stream = LiveStream::findOne(['wechat_app_id'=>$this->store_id]);
        $begin_time = \Yii::$app->request->get('begin_time');
        $end_time = $begin_time+3*3600*24*1000;
        //获取openid；
        $openid = $this->wechat->appId;
        $subopenid = substr($openid,-3);
        $rnum = $this->randnum(7);
        $treamId = $subopenid.$rnum;
        if(!$own_stream){
            $push_stream = $this->getPushUrl($ping_stream->push_stream,$treamId,"4c8e171be00a6fd563d37e4ad69f12ae",date('Y-m-d H:i:s',$end_time/1000));
//            $push_stream = $this->getPushUrl($ping_stream->push_stream,$treamId,"4c8e171be00a6fd563d37e4ad69f12ae",'2019-02-21 23:59:59');
            $pull_stream = $this->getPlayUrl($ping_stream->pull_stream,$treamId);
            $stream_form = new LiveStreamForm();
            $stream_form->wechat_app_id = $this->store_id;
            $stream_form->pull_stream = $pull_stream;
            $stream_form->push_stream = $push_stream;
            $stream_form->end_time = $end_time/1000;
            $stream_form->save();
        }else{
            if($begin_time>($own_stream->end_time*1000)){
                $stream_form = LiveStream::findOne(['wechat_app_id'=>$this->store_id]);
                $push_stream = $this->getPushUrl($ping_stream->push_stream,$treamId,"4c8e171be00a6fd563d37e4ad69f12ae",date('Y-m-d H:i:s',$end_time/1000));
                $pull_stream = $this->getPlayUrl($own_stream->pull_stream,$treamId);
            }else{
                $this->renderJson(array('code'=>0,'push_stream'=>$own_stream->push_stream));
            }
        }

        $stream_form->pull_stream = $pull_stream;
        $stream_form->push_stream = $push_stream;
        $stream_form->end_time = $end_time;
        $stream_form->save();
        $res_open = $form->save();
        $own_stream_new = LiveStream::findOne(['wechat_app_id'=>$this->store_id]);
        if($res_open->code==0){
            $this->renderJson(array('code'=>0,'push_stream'=>$own_stream_new->push_stream));
        }

//        $this->renderJson($form->save());

    }

//    //关闭直播
//    public function actionCloseLive()
//    {
//        $form = new CloseLiveForm();
//        $form->attributes = \Yii::$app->request->get();
//        $form->wechat_app_id = $this->store->id;
//        $this->renderJson($form->save());
//    }

    //查询直播时间
    public function actionLiveTime()
    {
        $form = new LiveTimeForm();
        $form->attributes = \Yii::$app->request->get();

        $this->renderJson($form->search());
    }

    //成交数据
    public function actionTodayOrder(){
        $start_time = strtotime(date('Y-m-d 00:00:00'));
        $end_time = strtotime(date('Y-m-d 23:59:59'));
        $order = Order::find() ->where([
            'store_id' =>$this->store_id,
            'is_delete' => 0,
            'is_pay' => 1,
        ]);
        $order ->andWhere(['>=', 'pay_time', $start_time]);
        $order ->andWhere(['<=', 'pay_time', $end_time]);
        $count = [];
        $num = $order->select('SUM(is_pay) AS num')->asArray()->one();
        $money = $order->select('SUM(pay_price) AS money')->asArray()->one();
        $count['num'] = floatval($num['num']);
        $count['money'] = floatval($money['money']);
        $count['adv'] = $count['money']/$count['num'];
        $this->renderJson($count);
    }

    //代发货订单
    public function actionDfhOrder(){
        $count = Order::find() ->where([
            'store_id' =>$this->store_id,
            'is_delete' => 0,
            'is_pay' => 1,
            'is_send' =>0,
        ])->count();
        $this -> renderJson($count);
    }

    //维权订单
    public function actionRefundingCount(){
        $count = OrderRefund::find() ->where([
            'store_id' =>$this->store_id,
            'is_delete' => 0,
            'status' =>0,
        ])->count();
        $this -> renderJson($count);
    }

    /**
     * 获取商品销量排行
     */
    public function actionGoodsSale()
    {
        $limit=\yii::$app->request->get('limit');
        $start_time = strtotime(date('Y-m-d 00:00:00'));
        $end_time = strtotime(date('Y-m-d 23:59:59'));
        $query = OrderDetail::find()->alias('od')
            ->leftJoin(['o' => Order::tableName()], 'od.order_id=o.id')
            ->leftJoin(['g' => Goods::tableName()], 'od.goods_id=g.id')
            ->where([
                'g.store_id' => $this->store_id,
                'g.is_delete' => 0,
                'o.is_delete' => 0,
                'o.is_pay' => 1,
                'od.is_delete' => 0,
            ]);
        $query->andWhere(['>=', 'o.addtime', $start_time]);
        $query->andWhere(['<=', 'o.addtime', $end_time]);
        $sale = $query->select('g.name,SUM(od.num) AS num')->groupBy('od.goods_id')->orderBy('num DESC')->limit($limit)->asArray()->all();
        $this->renderJson($sale);
    }
    //获取代理商下的分销订单
    public function actionShare()
    {

        $parent_id = \Yii::$app->request->get('parent_id');
        $form = new ShareOrderForm();
        $form->attributes = \Yii::$app->request->get();
        $form->store_id = $this->store->id;
        $form->parent_id = $parent_id ? (int)$parent_id : false;
//        $form->limit = 10;
        $data = $form->search();
        if ($parent_id) {
            $user = User::findOne(['store_id' => $this->store->id, 'id' => $parent_id]);
        }
//        $setting = Setting::findOne(['store_id' => $this->store->id]);
        return $this->renderJson( [
            'row_count' => $data['row_count'],
            'pagination' => $data['pagination'],
            'list' => $data['list'],
            //'count_data' => OrderListForm::getCountData($this->store->id),
//            'store_data' => $store_data_form->search(),
            'user' => $user,
//            'setting' => $setting
        ]);

    }
    public function actionResell()
    {
        $form = new ShareListForm();
        $form->attributes = \Yii::$app->request->get();
        $form->status = 1;
        $form->store_id = $this->store_id;
//        $form->limit = 10;
        $arr = $form->getList();
        $list = $form->getTeam();
        $count = $form->getCount();
//        $setting = Setting::findOne(['store_id' => $this->store->id]);
        return $this->renderJson( [
            'list' => $arr[0],
            'pagination' => $arr[1],
//            'setting' => $setting,
//            'team' => $list,
            'count' => $count,
        ]);
    }
    public function actionTeam()
    {
        $form = new ShareListForm();
        $form->attributes = \Yii::$app->request->get();
        $form->store_id = $this->store_id;
        $list = $form->getTeam();
        return $this->renderJson([
            'team'=>$list,
        ]);
    }
}